import React, { useEffect } from 'react';
import { setStore, STATE_CHANGED } from '@zny/hooks';
import microApp from '@/utils/microApp';
import mitt from 'mitt';
import { bus } from '@zny/utils';
import styles from './SubAppLayout.less';

const SubAppLayout: React.FC<any> = (props: any) => {
  const {
    bus: mainBus,
    MAIN_APP_EVENT,
    SUB_APP_EVENT_PREFIX,
    decorateTypeWithFlag,
    isEmit,
  } = microApp.get();

  useEffect(() => {
    console.log('=========================== subapp event listening  ======================== ');

    const mainEvent: mitt.Handler = (e: any) => {
      console.log(`main on ${MAIN_APP_EVENT} in sub`, e);
      console.log(`emit sub ${e.type}`);
      if (e.type === STATE_CHANGED) {
        const { key, state } = e.value;
        setStore(key, state);
        return;
      }
      bus.emit(decorateTypeWithFlag(e.type), e.value);
    };

    mainBus.on(MAIN_APP_EVENT, mainEvent);
    return () => {
      mainBus.off(MAIN_APP_EVENT, mainEvent);
    };
  }, []);
  useEffect(() => {
    const subEvent: mitt.WildcardHandler = (type: any, e: any) => {
      console.log('sub on *', type, e);
      if (isEmit(type)) {
        console.log(`emit main  ${SUB_APP_EVENT_PREFIX}${type}`);
        return mainBus.emit(`${SUB_APP_EVENT_PREFIX}${type}`, e);
      }
    };
    bus.on('*', subEvent);
    return () => {
      bus.off('*', subEvent);
    };
  }, []);
  return props.children;
};

export default SubAppLayout;
